<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
	<!-- 事件管理 -->
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<avue-crud
				ref="crud"
				v-model="form"
				:page="page"
				:data="tableData"
				:permission="permissionList"
				:table-loading="tableLoading"
				:option="tableOption"
				:before-open="handleOpenBefore"
				:cell-class-name="addClass"
				@on-load="getList"
				@search-change="searchChange"
				@refresh-change="refreshChange"
				@size-change="sizeChange"
				@current-change="currentChange"
				@cell-click="clickCell"
				@row-update="handleUpdate"
				@row-save="handleSave"
				@row-del="rowDel"
			>
				<template #eventStatus="{ row }">
					<el-tag v-if="row.eventStatus == '6'">未指派</el-tag>
					<el-tag v-if="row.eventStatus == '0'">待处理</el-tag>
					<el-tag type="warning" v-if="row.eventStatus == '1'">处理中</el-tag>
					<el-tag type="success" v-if="row.eventStatus == '2'">已处理</el-tag>
					<el-tag type="success" v-if="row.eventStatus == '3'">转工单</el-tag>
					<el-tag type="info" v-if="row.eventStatus == '4'">事件关闭</el-tag>
					<el-tag type="success" v-if="row.eventStatus == '5'">已评价</el-tag>
				</template>
				<template #menu="scope">
					<el-button
						type="primary"
						icon="el-icon-edit"
						text
						:disabled="scope.row.eventStatus === '4'"
						@click="$refs.crud.rowEdit(scope.row, scope.index)"
						>编辑
					</el-button>
					<el-button type="primary" text icon="el-icon-delete" @click="$refs.crud.rowDel(scope.row, scope.index)">删除 </el-button>
					<el-dropdown>
						<span class="el-dropdown-link" style="margin-left: 5px;">
							操作
							<el-icon class="el-icon--right" style="margin-left: -2px;">
								<arrow-down />
							</el-icon>
						</span>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item
									:disabled="
										scope.row.eventStatus === '0' ||
										scope.row.eventStatus === '1' ||
										scope.row.eventStatus === '2' ||
										scope.row.eventStatus === '3' ||
										scope.row.eventStatus === '4' ||
										scope.row.eventStatus === '5'
									"
									@click="appointEvent(scope.row)"
									>指派
								</el-dropdown-item>
								<el-dropdown-item
									:disabled="
										scope.row.eventStatus === '1' ||
										scope.row.eventStatus === '2' ||
										scope.row.eventStatus === '3' ||
										scope.row.eventStatus === '4' ||
										scope.row.eventStatus === '5' ||
										scope.row.eventStatus === '6' ||
										scope.row.handleUserId !== userId
									"
									@click="handlerEvent(scope.row)"
									>处理
								</el-dropdown-item>
								<el-dropdown-item
									:disabled="
										scope.row.eventStatus === '0' ||
										scope.row.eventStatus === '2' ||
										scope.row.eventStatus === '3' ||
										scope.row.eventStatus === '4' ||
										scope.row.eventStatus === '5' ||
										scope.row.eventStatus === '6'
									"
									@click="complateEvent(scope.row)"
									>完成
								</el-dropdown-item>
								<el-dropdown-item
									:disabled="
										scope.row.eventStatus === '2' ||
										scope.row.eventStatus === '3' ||
										scope.row.eventStatus === '4' ||
										scope.row.eventStatus === '5' ||
										scope.row.eventStatus === '6'
									"
									@click="changeEvent(scope.row)"
									>转工单
								</el-dropdown-item>
								<el-dropdown-item :disabled="scope.row.eventStatus === '4' || scope.row.eventStatus === '6'" @click="closeEvent(scope.row)"
									>关闭
								</el-dropdown-item>
								<el-dropdown-item
									:disabled="
										scope.row.eventStatus === '0' || scope.row.eventStatus === '1' || scope.row.eventStatus === '5' || scope.row.eventStatus === '6'
									"
									@click="appraiseEvent(scope.row)"
									>评价
								</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown>
				</template>
				<!-- <template #eventArea-form="{ row }">
            <avue-input-tree
              v-model="form.eventArea"
              :dic="treeLocationData"
              :props="defaultPropstree"
              type="tree"
              placeholder="请选择区域"
            ></avue-input-tree>
          </template> -->

				<!-- <template #eventArea-form>
					<avue-input-tree
						filterable
						v-model="form.eventArea"
						:dic="treeLocationData"
						:props="defaultProps"
						type="tree"
						placeholder="请选择事件区域"
					></avue-input-tree>
				</template> -->

				<!-- <template #modelType-form>
            <avue-select
              v-model="form.modelType"
              :dic="modelTypeData"
              :props="defaultProps5"
              placeholder="请选择设备类型"
            >
            </avue-select>
          </template>
          <template #devType-form>
            <avue-select
              v-model="form.devType"
              :dic="devTypeData"
              :props="defaultProps6"
              placeholder="请选择设备型号"
            >
            </avue-select>
          </template> -->
				<!-- <template #equipId-form>
            <avue-select
              :disabled="
                form.eventType == '2' ||
                form.eventType == '3' ||
                form.eventType == '4' ||
                form.eventType == '5' ||
                form.eventType == '6'
              "
              editDisabled
              v-model="form.equipId"
              :dic="deviceNameData"
              :props="defaultProps7"
              placeholder="请选择设备名称"
            >
            </avue-select>
          </template> -->
				<template #equipName-form>
					<div class="span-title">
						<div class="span-input">
							<el-input
								:disabled="form.eventType == '2' || form.eventType == '3' || form.eventType == '4' || form.eventType == '5' || form.eventType == '6'"
								v-model="form.equipName"
								placeholder="请选择设备"
							></el-input>
						</div>
						<div class="span-btn">
							<el-button
								type="primary"
								plain
								@click="getDevForm"
								:disabled="form.eventType == '2' || form.eventType == '3' || form.eventType == '4' || form.eventType == '5' || form.eventType == '6'"
								>选择设备
							</el-button>
						</div>
					</div>
				</template>
				<template #fileList-form>
					<ImgUpload @changeFile="changeFile" :fileData="fileData" />
				</template>
			</avue-crud>
		</div>
		<el-dialog v-if="dialogFormVisible" v-model="dialogFormVisible" title="指派事件" width="28%" @close="cancleDialog">
			<el-form-item label="处理部门" required>
				<avue-input-tree
					filterable
					v-model="handleDept"
					:dic="handleDeptData"
					:props="defaultProps1"
					placeholder="请选择处理部门"
					type="tree"
					style="width: 300px"
				>
				</avue-input-tree>
			</el-form-item>
			<el-form-item label="处理人员" required>
				<avue-select filterable v-model="handleUser" :dic="handleUserData" :props="defaultProps2" placeholder="请选择处理人员" style="width: 300px">
				</avue-select>
			</el-form-item>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancleDialog">取消</el-button>
					<el-button type="primary" @click="assignEvent"> 确定 </el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-if="dialogFormVisible3" v-model="dialogFormVisible3" title="评价工单" width="38%" @close="dialogFormVisible3 = false">
			<!-- <el-form-item label="满意程度">
          <el-rate v-model="rateValue" :max="5" show-score score-template="{value}分"></el-rate>
        </el-form-item> -->
			<el-form-item label="评价意见">
				<el-input type="textarea" v-model="confirmSug"></el-input>
			</el-form-item>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogFormVisible3 = false">取消</el-button>
					<el-button type="primary" @click="confirmAppraise"> 确定 </el-button>
				</span>
			</template>
		</el-dialog>
		<OmeventInfo ref="omeventInfo"></OmeventInfo>
		<DevForm ref="devFormRef" @getDeviceName="getDeviceName"></DevForm>
	</div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, fetchTree, operaEvent, getEventName } from '/@/api/om/omwevent';
import { getDeviceType, getDevtype, getAssets } from '/@/api/check/omicheckpoint';
import { getUserById, getDeptTree, getQueryUser } from '/@/api/om/omworder';
import OmeventInfo from './info/index.vue';
import DevForm from './devForm/index.vue';
import ImgUpload from '/@/components/ImageUpload/order.vue';
import { tableOption } from '/@/const/crud/om/omwevent';
// import {mapGetters} from 'vuex'

export default {
	name: 'omwevent',
	components: {
		OmeventInfo,
		DevForm,
		ImgUpload,
	},
	data() {
		return {
			form: {},
			treeLocationData: [],
			defaultPropstree: {
				label: 'name',
				value: 'id',
			},
			fileList: [],
			fileData: [],
			searchForm: {},
			tableData: [],
			orderUserData: [],
			modelTypeData: [],
			devTypeData: [],
			deviceNameData: [],
			defaultProps: {
				label: 'name',
				value: 'id',
			},
			defaultProps5: {
				label: 'bamAssetsTypeAlias',
				value: 'bamAssetsTypeCode',
			},
			defaultProps6: {
				label: 'bamAAssetsModelCn',
				value: 'bamAAssetsDeviceCode',
			},
			defaultProps7: {
				label: 'assetsName',
				value: 'assetsName',
			},
			page: {
				total: 0, // 总页数
				currentPage: 1, // 当前页数
				pageSize: 10, // 每页显示多少条
			},
			tableLoading: false,
			tableOption: tableOption,
			dialogFormVisible: false,
			handleDept: '',
			handleUser: '',
			handleDeptData: [],
			handleUserData: [],
			defaultProps1: {
				label: 'name',
				value: 'id',
			},
			defaultProps2: {
				label: 'name',
				value: 'userId',
			},
			dialogFormVisible3: false,
			confirmSug: '',
			eventNo: '',
			openType: '',
		};
	},
	computed: {
		// ...mapGetters(['permissions', 'userInfo']),
		permissionList() {
			return {
				// addBtn: this.validData(this.permissions.om_omwevent_add, false),
				// delBtn: this.validData(this.permissions.om_omwevent_del, false),
				// editBtn: this.validData(this.permissions.om_omwevent_edit, false)
			};
		},
		userId() {
			return JSON.parse(sessionStorage.getItem('pig-userInfo')).content.userId;
		},
	},
	watch: {
		'form.eventType': {
			handler(val, oldVal) {
				if (val && val !== oldVal && this.openType == 'add') {
					let type =
						val == 0
							? '设备报修'
							: '' || val == 1
							? '设备维保'
							: '' || val == 2
							? '卫生处理'
							: '' || val == 3
							? '纠纷处理'
							: '' || val == 4
							? '建筑设施'
							: '' || val == 5
							? '设施损坏'
							: '' || val == 6
							? '其他'
							: '';
					getEventName(type).then((res) => {
						this.form.eventName = res.data;
					});
				}
			},
		},

		'form.handleUserId': {
			handler(val, oldVal) {
				if (val) {
					getUserById(val).then((res) => {
						this.orderUserData = res.data;
						this.form.handleUserPhone = this.orderUserData.phone;
						this.form.handleUserName = this.orderUserData.name;
					});
				} else {
					this.form.handleUserPhone = '';
				}
			},
		},
		'form.assetsType': {
			handler(val, oldVal) {
				if (val && val !== oldVal) {
					getDeviceType({ bamAssetsTypeMcode: val }).then((res) => {
						this.modelTypeData = res.data;
					});
				} else {
					this.form.modelType = '';
				}
			},
		},
		'form.modelType': {
			handler(val, oldVal) {
				if (val && val !== oldVal) {
					getDevtype({ bamAAssetsModelCode: val }).then((res) => {
						this.devTypeData = res.data;
					});
				} else {
					this.form.devType = '';
				}
			},
		},
		'form.devType': {
			handler(val, oldVal) {
				if (val && val !== oldVal) {
					getAssets({ devType: val, eStatus: 1 }).then((res) => {
						this.deviceNameData = res.data;
					});
				} else {
					this.form.equipId = '';
				}
			},
		},
		'form.equipId': {
			handler(val, oldVal) {
				if (val && val !== oldVal) {
					let list = this.deviceNameData.find((item) => item.assetsName === val);
					if (list) {
						this.form.equipNo = list.deviceNo;
						this.form.equipName = list.assetsName;
					}
				}
			},
		},
		handleDept(val, oldVal) {
			if (val && val !== oldVal) {
				getQueryUser({deptId: val}).then((res) => {
					this.handleUserData = res.data.records;
					this.handleUser = '';
				});
			}
		},
	},
	methods: {
		// handleLocation() {
		//   fetchTree().then((response) => {
		//     this.treeLocationData = response.data.data
		//   })
		// },
		getList(page, params) {
			this.tableLoading = true;
			fetchList(
				Object.assign(
					{
						current: page.currentPage,
						size: page.pageSize,
					},
					params,
					this.searchForm
				)
			)
				.then((response) => {
					this.tableData = response.data.records;
					this.page.total = response.data.total;
					this.tableLoading = false;
				})
				.catch(() => {
					this.tableLoading = false;
				});
		},
		rowDel: function (row, index) {
			this.$confirm('是否确认删除事件' + '"' + row.eventNo + '"', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return delObj(row.evId);
				})
				.then((data) => {
					this.$message.success('删除成功');
					this.getList(this.page);
				})
				.catch((error) => {});
		},
		handleUpdate: function (row, index, done, loading) {
			row.handleType = 0 + '';
			putObj(row)
				.then((data) => {
					this.$message.success('修改成功');
					done();
					this.getList(this.page);
				})
				.catch(() => {
					loading();
				});
		},
		handleSave: function (row, done, loading) {
			row.handleType = 0 + '';

			addObj(row)
				.then((data) => {
					this.$message.success('添加成功');
					done();
					this.getList(this.page);
				})
				.catch(() => {
					loading();
				});
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
		},
		currentChange(current) {
			this.page.currentPage = current;
		},
		searchChange(form, done) {
			this.searchForm = form;
			this.page.currentPage = 1;
			this.getList(this.page, form);
			done();
		},
		refreshChange() {
			this.getList(this.page);
		},
		handleOpenBefore(show, type) {
			this.openType = type;
			//区域树
			fetchTree().then((res) => {
				this.treeLocationData = res.data.data;
			});
			if (type == 'add') {
				this.fileData = [];
				// this.$refs.devFormRef.selectRow = -1
			}
			if (type === 'edit') {
				this.fileData = this.form.fileList;
			}
			show();
		},
		handlerEvent(row) {
			this.$confirm('是否确认处理该事件', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				operaEvent({ eventNo: row.eventNo, eventStatus: 0 + '' }).then((res) => {
					this.$message.success('处理成功');
					this.getList(this.page);
				});
			});
		},
		complateEvent(row) {
			this.$confirm('是否确认完成事件', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				operaEvent({ eventNo: row.eventNo, eventStatus: 2 + '' }).then((res) => {
					this.$message.success('事件完成');
					this.getList(this.page);
				});
			});
		},
		changeEvent(row) {
			this.$confirm('是否确认转工单', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				operaEvent({ eventNo: row.eventNo, eventStatus: 3 + '' }).then((res) => {
					this.$message.success('转工单成功');
					this.getList(this.page);
				});
			});
		},
		closeEvent(row) {
			this.$confirm('是否确认关闭事件', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				operaEvent({ eventNo: row.eventNo, eventStatus: 4 + '' }).then((res) => {
					this.$message.success('关闭成功');
					this.getList(this.page);
				});
			});
		},

		// appraiseEvent(row) {
		//   this.$prompt('', '评价', {
		//     confirmButtonText: '确定',
		//     cancelButtonText: '取消'
		//   })
		//     .then(({ value }) => {
		//       let obj = {
		//         eventNo: row.eventNo,
		//         remark: value,
		//         eventStatus: 5
		//       }
		//       operaEvent(obj)
		//         .then((data) => {
		//           this.$message.success('评价成功')
		//           done()
		//         })
		//         .catch(() => {
		//           loading()
		//         })
		//     })
		//     .catch(() => {})
		// },
		appraiseEvent(row) {
			this.eventNo = row.eventNo;
			this.dialogFormVisible3 = true;
		},
		confirmAppraise() {
			let obj = {
				eventNo: this.eventNo,
				remark: this.confirmSug,
				eventStatus: 5 + '',
			};
			operaEvent(obj)
				.then((res) => {
					this.$message.success('事件已评价');
					this.dialogFormVisible3 = false;
					this.getList(this.page);
				})
				.catch((err) => this.$message.error(err));
		},
		addClass({ row, column, rowIndex, columnIndex }) {
			if (columnIndex === 1) {
				return 'cell-blue';
			}
		},
		// handleRowClick(row) {
		//   this.$refs.omeventInfo.dialogVisible = true
		//   this.$refs.omeventInfo.infoData = row
		// },
		clickCell(row, column, cell, event) {
			if (column.label === '事件编号') {
				this.$refs.omeventInfo.dialogVisible = true;
				this.$refs.omeventInfo.infoData = row;
			}
		},
		getDevForm() {
			this.$refs.devFormRef.visible = true;
			// this.$refs.devFormRef.getList(this.$refs.devFormRef.page)
		},
		getDeviceName(list) {
			this.form.equipName = list.deviceName;
			this.form.equipNo = list.deviceNo;
			this.form.eventArea = list.placeno;
		},
		changeFile(list) {
			this.form.fileList = list;
			this.form.fileList.forEach((item) => {
				item.eventNo = this.form.eventNo;
			});
		},
		appointEvent(row) {
			this.dialogFormVisible = true;
			this.eventNo = row.eventNo;
			getDeptTree().then((res) => {
				this.handleDeptData = res.data;
			});
		},
		cancleDialog() {
			this.dialogFormVisible = false;
			this.handleDept = '';
			this.handleUser = '';
		},

		assignEvent() {
			let obj = {
				eventNo: this.eventNo,
				eventStatus: 6 + '',
				handleUserDeptId: this.handleDept,
				handleUserId: this.handleUser,
			};
			if (obj.handleUserDeptId && obj.handleUserId) {
				operaEvent(obj)
					.then((res) => {
						this.$message.success('事件指派成功');
						this.handleDept = '';
						this.handleUser = '';
						this.dialogFormVisible = false;
						this.getList(this.page);
					})
					.catch((err) => this.$message.error(err));
			} else {
				this.$message.warning('请选择处理部门和处理人员');
			}
		},
	},
};
</script>
<style lang="scss" scoped>
.span-title {
	display: flex;

	.span-input {
		flex: 2;
	}
}

.theme-white .el-dropdown {
	margin-top: 7px;
}

// ::v-deep .el-table__row {
//   cursor: pointer !important;
// }
// ::v-deep .el-input__inner {
//   cursor: pointer;
// }
::v-deep .avue-crud__menu {
	display: flex;
	align-items: center;
}
</style>
<style>
.cell-blue {
	cursor: pointer !important;
	color: #409eff !important;
}
</style>
